package ClientTests;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.io.PrintWriter;
import java.net.Socket;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;
import java.rmi.*;

/*
 * Author: David Swords
 * Email: davidswordster@gmail.com
*/

public class Server
{
	public static final String SERVICE_TYPE = "music_service._udp.localhost.";
	public static final String SERVICE_NAME = "media_center";
	public static final int SERVICE_PORT = 1234;
	private int backlog = 10;
	private ServerSocket serverSocket;

	public Server()
	{
		try
		{
			serverSocket = new ServerSocket(SERVICE_PORT, backlog);
			System.out.println("The server has started and is listening on "+SERVICE_PORT);
		}
		catch (IOException ioe)
		{
			ioe.printStackTrace();
		}
		catch (SecurityException se)
		{
			se.printStackTrace();
		}
	}

	public void listen()
	{
		while(true)
		{
			try
			{
				Socket socket = serverSocket.accept();
				BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				String message = inFromClient.readLine();
				//System.out.println("Message from client: " + message);
				PrintWriter outToClient = new PrintWriter(socket.getOutputStream(), true);
				if(message.equals("CLIENT"))
					outToClient.println("SERVER");
				inFromClient.close();
				socket.close();
			}
			catch(IOException ioe)
			{
				ioe.printStackTrace();
			}
			catch(SecurityException se)
			{
				se.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws IOException
	{
		JmDNS jmdns = JmDNS.create();
		System.out.println("fire in the hole!");
		ServiceInfo info = ServiceInfo.create(SERVICE_TYPE, SERVICE_NAME, SERVICE_PORT,0,0,"a_property=some_value");
		jmdns.registerService(info);
		System.out.println("Registered Service as "+info);
		Server server = new Server();
		
		try
		{
			System.setSecurityManager(new RMISecurityManager());
			System.out.println("Security Manager Set.");
    		RMIServerImpl Server = new RMIServerImpl();
    		System.out.println("RMISERVER Instansiated");
			Naming.rebind("SAMPLE-SERVER" , Server);
			System.out.println("Server name binded.");
    		System.out.println("Server waiting.....");
		}
		catch (java.net.MalformedURLException me)
      		{
         		System.out.println("Malformed URL: " + me.toString());
      		}
    		catch (RemoteException re)
      		{
         		System.out.println("Remote exception: " + re.toString());
     	 	}
		server.listen();
		jmdns.unregisterService(info);
		jmdns.close();				
	}
}